package com.pzl.base.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.io.Serializable;

import butterknife.ButterKnife;


/**
 * 碎片基类
 */
public abstract class BaseFragment extends Fragment {

    protected Context mContext;

    protected LayoutInflater mInflater;

    protected Bundle argumentsBundle;

    protected View mRoot;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mContext = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        argumentsBundle = getArguments();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (mRoot != null) {
            ViewGroup parent = (ViewGroup) mRoot.getParent();
            if (parent != null)
                parent.removeView(mRoot);
        } else {
            mInflater = inflater;
            mRoot = mInflater.inflate(getLayoutId(), container, false);
            // Do something
            onBindViewBefore(mRoot);
            // Bind view
            ButterKnife.bind(this, mRoot);
            // Get savedInstanceState
            if (savedInstanceState != null)
                onRestartInstance(savedInstanceState);
            // Init
            initData();
        }
        return mRoot;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        argumentsBundle = null;
    }

    protected abstract int getLayoutId();

    /**
     *
     * @param resId
     * @return
     */
    protected View inflateView(int resId) {
        return mInflater.inflate(resId, null);
    }

    /**
     *
     * @param viewId
     * @param <T>
     * @return
     */
    protected <T extends View> T findView(int viewId) {
        return (T) mRoot.findViewById(viewId);
    }

    protected <T extends Serializable> T getBundleSerializable(String key) {
        if (argumentsBundle == null) {
            return null;
        }
        return (T) argumentsBundle.getSerializable(key);
    }

    public boolean onBackPressed() {
        return false;
    }

    protected void onBindViewBefore(View root) {
    }

    protected void onRestartInstance(Bundle bundle) {
    }

    protected void initData() {
    }


}
